package com.ruoyi.eqmonitor.smdtv.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.eqmonitor.dtos.OptDeviceDto;
import com.ruoyi.eqmonitor.smdtv.domain.SmdtvHydrologicStation;
import com.ruoyi.eqmonitor.smdtv.dtos.HydrologicStationDto;
import com.ruoyi.eqmonitor.smdtv.mapper.SmdtvHydrologicStationMapper;
import com.ruoyi.eqmonitor.smdtv.service.ISmdtvHydrologicStationService;
import com.ruoyi.eqmonitor.utils.HydrologicStationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 水文站Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-03-28
 */
@Service
public class SmdtvHydrologicStationServiceImpl extends ServiceImpl<SmdtvHydrologicStationMapper,SmdtvHydrologicStation> implements ISmdtvHydrologicStationService {
    
    @Autowired
    private SmdtvHydrologicStationMapper smdtvHydrologicStationMapper;

    @Override
    public SmdtvHydrologicStation selectSmdtvHydrologicStationById(String id){
        return smdtvHydrologicStationMapper.selectSmdtvHydrologicStationById(id);
    }
      
    @Override
    public List<SmdtvHydrologicStation> selectSmdtvHydrologicStationList(SmdtvHydrologicStation smdtvHydrologicStation){
        return smdtvHydrologicStationMapper.selectSmdtvHydrologicStationList(smdtvHydrologicStation);
    }

    @Override
    public List<SmdtvHydrologicStation> getAll() {
        return smdtvHydrologicStationMapper.selectSmdtvHydrologicStationList(new SmdtvHydrologicStation());
    }

    @Override
    public boolean upStations() {
        //清空再新增
        boolean remove = this.remove(new LambdaQueryWrapper<>());
        if (remove){
            Map<String, String> param = new HashMap<>();
            String stations = HydrologicStationUtil.doGet("stations", param);
            JSONObject jsonObject = JSON.parseObject(stations);
            Object data = jsonObject.get("data");
            String dataString = JSONArray.toJSONString(data);
            List<String> dataList= JSONArray.parseArray(dataString,String.class);
            List<SmdtvHydrologicStation> list = new ArrayList<>();
            for (String s : dataList){
                JSONObject map = JSON.parseObject(s);
                String id = map.get("id").toString().trim();
                String name = map.get("name").toString().trim();
                String lng = map.get("lng").toString();
                String lat = map.get("lat").toString();
                String type = map.get("type").toString();
                String type_name = map.get("type_name").toString();
                String address = map.get("address").toString().trim();
                String areacode = map.get("areacode").toString();
                SmdtvHydrologicStation station = new SmdtvHydrologicStation();
                station.setId(id);
                station.setName(name);
                station.setLng(lng);
                station.setLat(lat);
                station.setType(type);
                station.setTypeName(type_name);
                station.setAddress(address);
                station.setAreacode(areacode);
                station.setUpdateTime(new Date());
                list.add(station);
            }
            return this.saveBatch(list);
        }else {
            return false;
        }
    }

    @Override
    public List<SmdtvHydrologicStation> getDetail(HydrologicStationDto dto) {
        //处理时间参数,时间参数不存在则取当天时间
        String[] timeDto = dto.getTime();
        String time;
        if (timeDto == null){
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            String format = sdf.format(date);
            String time1 = format.replace(" ", "T");

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String format2 = sdf2.format(date);
            String time2 = format2.replace(" ", "T");

            String[] strings = {time1,time2};
            time = Arrays.toString(strings);
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            //计算时间差
            long l = 0;
            try {
                l = (sdf.parse(timeDto[1]).getTime() - sdf.parse(timeDto[0]).getTime()) / 24 / 60 / 60 / 1000;
            } catch (ParseException e) {
                log.error("查询水位数据列表处理时间参数错误");
                e.printStackTrace();
            }
            if (l > 2){
                // 抛出异常
                throw new RuntimeException("时间间隔不能大于48小时");
            }
            timeDto[0] = timeDto[0].replace(" ", "T");
            timeDto[1] = timeDto[1].replace(" ", "T");
            time = Arrays.toString(timeDto);
        }

        //查询测站数据列表，判断更新时间是否大于3天，是则更新
        String[] id = dto.getIds();
        if (id == null){
            id = this.getAll().stream().map(SmdtvHydrologicStation::getId).distinct().toArray(String[]::new);
        }
        LambdaQueryWrapper<SmdtvHydrologicStation> lqw = new LambdaQueryWrapper<>();
        lqw.in(SmdtvHydrologicStation::getId,id);
        List<SmdtvHydrologicStation> station = smdtvHydrologicStationMapper.selectList(lqw);
        Date updateTime = station.get(0).getUpdateTime();
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c2.setTime(updateTime);
        int i1 = c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);
        if (i1 > 3){
            this.upStations();
        }

        //查询数据
        Map<String, String> param = new HashMap<>();
        param.put("time",time);
        String detail = HydrologicStationUtil.doGetByIds("water/detail", param,id);
        //处理数据
        JSONObject jsonObject = JSON.parseObject(detail);
        boolean success = (boolean)jsonObject.get("success");
        if (success){
            Object data = jsonObject.get("data");
            String dataString = JSONArray.toJSONString(data);
            List<String> dataList= JSONArray.parseArray(dataString,String.class);
            for (String s : dataList){
                JSONObject json = JSON.parseObject(s);
                Object data1 = json.get("data");
                String dataString1 = JSONArray.toJSONString(data1);
                List<String> dataList1 = JSONArray.parseArray(dataString1,String.class);
                if (dataList1.size() > 0){
                    BigDecimal sumVal = new BigDecimal("0");
                    int i = 0;
                    BigDecimal sumMVal = new BigDecimal("0");
                    int j = 0;
                    for (String s1 : dataList1){
                        JSONObject json1 = JSON.parseObject(s1);
                        Object val = json1.get("val");
                        if (val != null){
                            sumVal = sumVal.add(new BigDecimal(val.toString()));
                            i++;
                        }
                        Object mval = json1.get("mval");
                        if (mval != null){
                            sumMVal = sumMVal.add(new BigDecimal(mval.toString()));
                            j++;
                        }
                    }
                    if (i != 0){
                        BigDecimal divide = sumVal.divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP);
                        for (SmdtvHydrologicStation hs : station){
                            if (json.get("id").toString().equals(hs.getId())){
                                hs.setVal(divide.toString());
                                break;
                            }
                        }
                    }
                    if (j != 0){
                        BigDecimal divide1 = sumMVal.divide(new BigDecimal(j), 2, BigDecimal.ROUND_HALF_UP);
                        for (SmdtvHydrologicStation hs : station){
                            if (json.get("id").toString().equals(hs.getId())){
                                hs.setMval(divide1.toString());
                                break;
                            }
                        }
                    }
                }
            }
        }
        return station;
    }
}
